<template>
  <el-dialog
  :title="title"
  :visible.sync="visible"
  width="40%"
  :before-close="handleClose">
    <el-form :model="formData" :rules="rules" ref="formData" label-width="100px" class="demo-ruleForm" style="width:90%">
    <el-form-item label="新密码：" prop="newPassword">
        <el-input v-model="formData.newPassword" show-password placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item label="确认密码：" prop="rePassword">
        <el-input v-model="formData.rePassword" show-password placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item>
        <el-button type="primary" size="mini" @click="submitForm('formData')">确定</el-button>
        <el-button @click="handleClose" size="mini">取消</el-button>
    </el-form-item>
    </el-form>
    </el-dialog>
</template>

<script>
import * as api from '@/api/user'

export default {
    data() {
        let validatePass = (rule, value, callback) => {
            if (value !== this.formData.newPassword) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            
            rules: {
                newPassword: [
                    { required: true, message: '新密码不能为空', trigger: 'blur' }                    
                ],
                rePassword: [
                    { required: true, message: '确认密码不能为空', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' }                    
                ],
            },
            formData:{}
        }
    },
    props:{
        userId: null, // 用户id
        visible:{
            type:Boolean,
            default:false
        },
        remoteClose: Function 
    },
    methods: {
        // 关闭窗口
        handleClose(){
            this.$refs.formData.resetFields()
            this.remoteClose()
        },
        // 提交表格，验证
        submitForm(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.formData.userId = this.userId
                    this.submitData()
                } else {
                    this.$message({
                    message: '保存失败',
                    type: 'error'
                    });
                    return false;
                }
            });
        },
        async submitData(){
            let response = await api.updatePassword(this.formData)
            
            if (response.code === 20000){
                this.$message({
                    message: '修改成功',
                    type: 'success'
                    });
                this.handleClose()
                
            }else{
                this.$message({
                    message: '修改失败',
                    type: 'error'
                    });
            }
        }
    },
}
</script>

<style>

</style>